import ampub from 'ampub';
import moment from 'moment';
import { ajax, LocalToDongbaTime } from 'nc-lightapp-front';
import { enableDailyInterest, enableMonthlyInterest } from '.';
import constants from '../../constants';
import afterEvent from './afterEvent';
import { setUsufructassetBtns } from './setStatus';
import { simpleTraceabilityDominate, stepLease } from './usufructAssetHandler';


const {
	URL,
	CALCULATELEASELIABILITIESFIELD: calculateLeaseLiabilitiesField,
	AREA: {
		CARD: {
			STEPRENTSTANDARD_TAB: steprentstandard_tab,
			DEPACCRUAL_TAB_MONTH: depaccrual_tab_month,
			BASIC_INFO_AREA: basicInfoForm
		}
	}
} = constants;

const { utils: { multiLangUtils: { getMultiLangByID }, msgUtils: { showMessage } } } = ampub;
/**
 * 使用权资产的编辑后事件处理
 *
 * @param props
 * @param moduleId
 * @param field
 * @param newValue
 * @param oldValue
 * @param record
 */

export default function usufructAssetAfterEvent(props, moduleId, field, newValue, oldValue, record) {
    const { form, cardTable, getUrlParam } = props;
    //租赁负债相关的字段进行修改后需要重新计算租赁负债
    calculateLeaseLiabilitiesField.includes(field) ? (this.isNeedCalculateLeaseLiabilities = true) : "";
    //税码
    if (field == "tax_code") {
        if (newValue.value) {
            queryTaxrate(props, moduleId, field, newValue, oldValue, record);
        } else {
            form.setFormItemsValue(basicInfoForm, {
                tax_rate: { value: null, display: null }
            });
        }
    }

    //阶梯租金
    if (field == "step_rent") {
        let { value: step_rent } = newValue;

        setUsufructassetBtns.call(this, getUrlParam("status"));

        this.bodyTabDataManager.setTabVOs(this.curr_pk_card, null, steprentstandard_tab, {});
        cardTable.setTableData(steprentstandard_tab, { rows: [] });

        cardTable.toggleCardTable(steprentstandard_tab, step_rent);
        // 租金标准
        form.setFormItemsDisabled(basicInfoForm, { rent_standard: step_rent });
        form.setFormItemsRequired(basicInfoForm, { rent_standard: !step_rent });

        if (step_rent) {
            // 精度
            cardTable.setColScale([{ areacode: steprentstandard_tab, fieldcode: "rent", scale: this.originvalue_digit }]);
            let starting_date = form.getFormItemsValue(basicInfoForm, "starting_date").value;
            cardTable.addRow(steprentstandard_tab, 0, { start_date: { value: starting_date } }, true);
            // 租金标准
            form.setFormItemsValue(basicInfoForm, { rent_standard: { value: null, display: null, scale: this.originvalue_digit} });
        }else{
			form.setFormItemsValue(basicInfoForm, { step_lease_flag: { value: false, display: null} });
		}
    }

    /* 按阶梯租金计租 */
	if (field == 'step_lease_flag') {
        /* 阶梯租金 */
		let step_rent = form.getFormItemsValue(moduleId, 'step_rent').value;
		if (!step_rent && newValue.value) {
            /* 国际化："201201504A-0000102": "当阶梯租金为是时，才可以按阶梯租金计租！" */
		    showMessage(props, { content: getMultiLangByID('201201504A-0000102'), color: 'warning' });
            form.setFormItemsValue(basicInfoForm, { step_lease_flag: oldValue });
		}
	}

    //起算日期
    if (field == "starting_date") {
        if (newValue.value) {
            let step_rent = form.getFormItemsValue(basicInfoForm, "step_rent").value;
            if (step_rent) {
                const rows = cardTable.getNumberOfRows(steprentstandard_tab);
                if (rows) {
                    cardTable.setValByKeyAndIndex(steprentstandard_tab, 0, "start_date", newValue);
                }
            }
            form.setFormItemsValue(basicInfoForm, {
                starting_date: newValue
            });
        }
    }

    //起租日期
    if (field == "rentstart_date") {
        if (newValue.value) {
            /* 同步起算日期，当该起算日期不存在时 */
            const starting_date_val = form.getFormItemsValue(basicInfoForm, "starting_date").value;
            if (!starting_date_val) {
                form.setFormItemsValue(basicInfoForm, {
                    starting_date: newValue
                });
            }
            let step_rent = form.getFormItemsValue(basicInfoForm, "step_rent").value;
            if (step_rent) {
                // 同步阶梯租金开始日期，当该开始日期不存在时
                const rows = cardTable.getNumberOfRows(steprentstandard_tab);
                if (rows) {
                    const step_start_date_val = cardTable.getValByKeyAndIndex(steprentstandard_tab, 0, "start_date").value;
                    if (!step_start_date_val) {
                        cardTable.setValByKeyAndIndex(steprentstandard_tab, 0, "start_date", newValue);
                    }
                }
            }
        }
    }

    //止租日期
    if (field == "ending_date") {
        if (newValue.value) {
            /* 按阶梯租金计租 */
            let step_lease_flag = form.getFormItemsValue(basicInfoForm, "step_lease_flag").value;
            if (step_lease_flag === true) {
                /* 同步阶梯租金最后一行截止日期 */
                const rows = cardTable.getNumberOfRows(steprentstandard_tab);
                cardTable.setValByKeyAndIndex(steprentstandard_tab, rows - 1, "end_date", newValue);
            }
        }
    }

    if (
        /* 租金拆分 */
        field == "rent_split_flag" ||
        /* 起租日期 */
        field == "rentstart_date" ||
        /* 续租选择权 */
        field == "renewal_flag" ||
        /* 续租截止日期 */
        field == "relet_ending_date" ||
        /* 止租日期 */
        field == "ending_date" ||
        /* 衔接处理办法 */
        field == "cohesion_process"
    ) {
        /* 简单追溯控制 */
        simpleTraceabilityDominate.call(this, field);
    }

    //合同生效日期
    if (field == "contract_effect_date") {
        if (newValue.value) {
            let formatDate = moment(newValue.value, "YYYY-MM-DD HH:mm:ss").hours(0).minutes(0).seconds(0);
            // newValue.value = DongbaToLocalTime(formatDate).format('YYYY-MM-DD HH:mm:ss');
            newValue.value = LocalToDongbaTime(formatDate).format("YYYY-MM-DD HH:mm:ss");
            form.setFormItemsValue(basicInfoForm, {
                rentstart_date: newValue
            });
            form.setFormItemsValue(basicInfoForm, {
                starting_date: newValue
            });
        }
    }
    //续租选择权
    if (field == "renewal_flag") {
        /* 按阶梯租金计租 */
        let step_lease_flag = form.getFormItemsValue(basicInfoForm, "step_lease_flag").value;
        if (newValue.value) {
            if (step_lease_flag === true) {
                /* 同步阶梯租金最后一行截止日期 */
                const rows = cardTable.getNumberOfRows(steprentstandard_tab);
                let relet_ending_date = form.getFormItemsValue(basicInfoForm, "relet_ending_date");
                if (relet_ending_date.value){
                    cardTable.setValByKeyAndIndex(steprentstandard_tab, rows - 1, "end_date", relet_ending_date);
                }
            }
        } else {
            form.setFormItemsValue(basicInfoForm, {
                relet_ending_date: { value: "", display: "" }
            });

            if (step_lease_flag === true) {
                /* 同步阶梯租金最后一行截止日期 */
                const rows = cardTable.getNumberOfRows(steprentstandard_tab);
                let ending_date = form.getFormItemsValue(basicInfoForm, "ending_date");
                if (ending_date.value){
                    cardTable.setValByKeyAndIndex(steprentstandard_tab, rows - 1, "end_date", ending_date);
                }
            }
        }
    }

    //续租截止日期
    if (field == "relet_ending_date") {
        if (newValue.value){
            /* 同步阶梯租金最后一行截止日期 */
            const rows = cardTable.getNumberOfRows(steprentstandard_tab);
            cardTable.setValByKeyAndIndex(steprentstandard_tab, rows - 1, "end_date", newValue);
        }
    }

    //购买选择权
    if (field == "purchase_choice") {
        if (!newValue.value) {
            form.setFormItemsValue(basicInfoForm, {
                purchase_price: { value: null, display: null }
            });
        }
    }
    // 计息方式 1-按月
    if (field == "interest_base") {
        if (newValue.value == 1) {
            this.setState({ isaccruedbymonth: true }, () => {
                enableMonthlyInterest.call(this);
            });
        } else {
            this.setState({ isaccruedbymonth: false }, () => {
                enableDailyInterest.call(this);
            });
        }
        // 清空表格数据
        cardTable.setTableData(depaccrual_tab_month, { rows: [] });
    }

    // 预计还原成本
    if (field == "expect_restore_cost") {
        form.setFormItemsValue(basicInfoForm, {
            expect_liabilities: { value: null, display: null }
        });
    }

    // 经办人反带经办部门
    if (field === "pk_transactor") {
        let pk_handledept_v = form.getFormItemsValue(basicInfoForm, "pk_handledept_v").value;
        if (!pk_handledept_v && newValue.value) {
            afterEvent.call(this, props, moduleId, field, newValue, oldValue, record, null, false);
        }
    }

    // 按阶梯租金计租
    if (field === "step_lease_flag") {
        stepLease.call(this);
    }
}

function queryTaxrate(props, moduleId, field, newValue, oldValue, record) {
	const { form } = props;
	if (newValue && newValue.value) {
		let data = { pk_taxcode: newValue.value };
		ajax({
			url: URL.COMMONPARAMETERSQUERY,
			data,
			success: (res) => {
				let { success, data } = res;
				if (success && data) {
					form.setFormItemsValue(basicInfoForm, {
						tax_rate: { value: data.tax_rate || null }
					});
				}
			}
		});
	}
}

/**
 * 查询税率
 * 
 * @param {税码主键} pk_taxcode 
 * @returns 
 */
async function queryTaxRatePromise(pk_taxcode) {
    if(!pk_taxcode){
        return null;
    }

    return new Promise((resolve, reject) => {
        let urlData = { pk_taxcode };
        ajax({
            url: URL.COMMONPARAMETERSQUERY,
            data: urlData,
            success: (res) => {
                let { success, data } = res;
                if (success && data) {
                    resolve(data.tax_rate);
                } else {
                    reject(null);
                }
            }
        });
    });
}

export { queryTaxRatePromise };

